package cn.itsource.ymcc.config;

import cn.itsource.ymcc.domain.Permission;
import cn.itsource.ymcc.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)//开启注解支持
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private IPermissionService permissionService;

    //密码编码器：不加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 这个代码写着有点复制  你可以C 但是你要知道每一句代码是什么意思
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        FormLoginConfigurer<HttpSecurity> configurer = http.formLogin()    //允许表单登录  默认就有表单
                .successForwardUrl("/loginSuccess");

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = configurer   //登录成功就去哪里
                .and().authorizeRequests()                                //授权配置
                .antMatchers("/auth/accountLogin").permitAll(); //

          //登录路径放行
        List<Permission> list = permissionService.list();
        for (Permission permission : list) {
            registry.antMatchers(permission.getResource())
                    .hasAuthority(permission.getSn());//需要什么权限
        }

        registry.anyRequest().authenticated()                   //其他路径都要认证之后才能访问
        .and().logout().permitAll()                    //登出路径放行 /logout
        .and().csrf().disable();                        //关闭跨域伪造检查(自己去研究)  可以提供效率
    }

    @Bean
    public AuthenticationManager getAuthenticationManager() throws Exception {
        return super.authenticationManager();
    }
}
